﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Veracruz.IdentityModel;
using Microsoft.IdentityModel.Claims;
using System.Threading;
using System.IdentityModel.Tokens;
using Veracruz.Facebook.IdentityModel;

namespace Veracruz.Facebook.Services
{
    [ServiceContract(ConfigurationName="DuderContract")]
    public interface IDuder
    {
        [OperationContract(Name = "GetFriends")]
        string[] GetFriends();
    }
    // NOTE: If you change the class name "Duder" here, you must also update the reference to "Duder" in Web.config.
[ServiceBehavior(ConfigurationName="DuderService")]
    public class Duder : IDuder
    {

        private UserInfo[] GetFriendFullDetails()
        {
            // Get the caller's identity.
            IClaimsIdentity identity = ((IClaimsPrincipal)Thread.CurrentPrincipal).Identity as IClaimsIdentity;


            if (!identity.Claims.Exists(delegate(Claim claim) { return claim.ClaimType == IdentityClaimDefinitions.AuthenticationTokenClaim; }))
            {
                throw new SecurityTokenException("AuthenticationTokenClaim not found");
            }
            Claim l_authenticationTokenClaim = identity.Claims.Single<Claim>(claim => claim.ClaimType == IdentityClaimDefinitions.AuthenticationTokenClaim);
            Claim l_sessionKeyClaim = identity.Claims.Single<Claim>(claim => claim.ClaimType == IdentityClaimDefinitions.SessionKeyClaim);
            Claim l_uniqueIdentifierClaim = identity.Claims.Single<Claim>(claim => claim.ClaimType == IdentityClaimDefinitions.UniqueIdentifierClaim);

            return FacebookHelper.GetFriends(identity.GetSession(), l_uniqueIdentifierClaim.Value);


        }

        public string[] GetFriends()
        {
            UserInfo[] l_userInfos = GetFriendFullDetails();

            List<string> l_nameList = new List<string>();
            for (int i = 0; i < l_userInfos.Length; i++)
            {
                l_nameList.Add(l_userInfos[i].Name);
            }
            return l_nameList.ToArray();
        }
    }
}
